package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.venueservice.consts.CommonConstants;
import com.eastfair.venueservice.dao.ServiceProviderAuditHistoryMapper;
import com.eastfair.venueservice.dto.ServiceProviderAuditHistoryDTO;
import com.eastfair.venueservice.entity.ServiceProviderAuditHistory;
import com.eastfair.venueservice.exceptioncode.VenueServiceExceptionCode;
import com.eastfair.venueservice.service.ServiceProviderAuditHistoryService;
import com.eastfair.venueservice.vo.ServiceProviderAuditHistoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 服务商审核历史表
 * </p>
 *
 * @author gj
 * @date 2022-07-13
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ServiceProviderAuditHistoryServiceImpl extends SuperServiceImpl<ServiceProviderAuditHistoryMapper, ServiceProviderAuditHistory> implements ServiceProviderAuditHistoryService {

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ServiceProviderAuditHistory> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(ServiceProviderAuditHistory model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public IPage<ServiceProviderAuditHistoryVO> listServiceProviderAuditHistoryVOs(PageParams<ServiceProviderAuditHistoryDTO> pageParams) {
        log.info("listServiceProviderAuditHistoryVOs - 查询审核历史VO列表, pageParams={}", pageParams);
        IPage<ServiceProviderAuditHistory> page = listServiceProviderAuditHistories(pageParams);
        IPage<ServiceProviderAuditHistoryVO> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);
        List<ServiceProviderAuditHistory> records = page.getRecords();
        if (records == null || records.isEmpty()) {
            return voPage;
        }
        List<ServiceProviderAuditHistoryVO> serviceProviderAuditHistoryVOList = records
                .stream()
                .map(serviceProvider -> BeanUtil.toBean(serviceProvider, ServiceProviderAuditHistoryVO.class))
                .collect(Collectors.toList());
        voPage.setRecords(serviceProviderAuditHistoryVOList);
        return voPage;
    }

    @Override
    public IPage<ServiceProviderAuditHistory> listServiceProviderAuditHistories(PageParams<ServiceProviderAuditHistoryDTO> pageParams) {
        log.info("listServiceProviderAuditHistories - 查询审核历史列表, pageParams={}", pageParams);
        ServiceProviderAuditHistoryDTO query = pageParams.getModel();
        QueryWrapper<ServiceProviderAuditHistory> queryWrapper = createServiceProviderAuditHistoryQueryWrapper(query);
        IPage<ServiceProviderAuditHistory> page = pageParams.buildPage();
        return page(page, queryWrapper);
    }

    @Override
    public List<ServiceProviderAuditHistory> listServiceProviderAuditHistories(ServiceProviderAuditHistoryDTO param) {
        log.info("listServiceProviderAuditHistories - 查询服务商审核历史列表, param={}", param);
        QueryWrapper<ServiceProviderAuditHistory> queryWrapper = createServiceProviderAuditHistoryQueryWrapper(param);
        return list(queryWrapper);
    }

    @Override
    public List<ServiceProviderAuditHistory> listByServiceProviderId(Long serviceProviderId) {
        log.info("listByServiceProviderId - 服务商ID查询服务商列表, serviceProviderId={}", serviceProviderId);
        ServiceProviderAuditHistoryDTO param = new ServiceProviderAuditHistoryDTO();
        param.setServiceProviderId(serviceProviderId);
        return listServiceProviderAuditHistories(param);
    }

    @Override
    public ServiceProviderAuditHistoryVO getVOById(Long id) {
        log.info("getServiceProviderAuditHistoryVOById - id 查询审核历史详情, id={}", id);
        ServiceProviderAuditHistory serviceProviderAuditHistory = getById(id);
        if (serviceProviderAuditHistory == null) {
            throw BizException.wrap(VenueServiceExceptionCode.SERVICE_PROVIDER_AUDIT_HISTORY_NOT_EXIST);
        }
        return BeanUtil.toBean(serviceProviderAuditHistory, ServiceProviderAuditHistoryVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveServiceProviderAuditHistory(ServiceProviderAuditHistoryDTO historyDTO) {
        log.info("saveServiceProviderAuditHistory - 保存服务商审核历史={}", historyDTO);
        ServiceProviderAuditHistory history = BeanUtil.toBean(historyDTO, ServiceProviderAuditHistory.class);
        return save(history);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyBatchNewAuditHistory(Long sourceServiceProviderId, Long targetServiceProviderId, Long targetServiceProviderAuditId) {
        log.info("copyBatchNewServiceProviderAuditHistory - 批量复制审核历史, sourceServiceProviderId={}, targetServiceProviderId={}",
                sourceServiceProviderId, targetServiceProviderId);
        List<ServiceProviderAuditHistory> sourceList = listByServiceProviderId(sourceServiceProviderId);
        if (sourceList == null || sourceList.isEmpty()) {
            return true;
        }
        CopyOptions copyOptions = CopyOptions
                .create()
                .setIgnoreProperties(CommonConstants.COMMON_IGNORE_PROPERTIES);
        List<ServiceProviderAuditHistory> targetList = sourceList
                .stream()
                .map(serviceProviderAuditHistory -> {
                    ServiceProviderAuditHistory targetServiceProviderAuditHistory
                            = BeanUtil.toBean(serviceProviderAuditHistory, ServiceProviderAuditHistory.class, copyOptions);
                    targetServiceProviderAuditHistory.setServiceProviderId(targetServiceProviderId);
                    targetServiceProviderAuditHistory.setServiceProviderAuditId(targetServiceProviderAuditId);
                    return targetServiceProviderAuditHistory;
                })
                .collect(Collectors.toList());
        targetList.forEach(this::save);
        return true;
    }

    @Override
    public boolean asyncCopyBatchNewAuditHistory(Long sourceServiceProviderId, Long targetServiceProviderId, Long targetServiceProviderAuditId) {
        threadPoolTaskExecutor.execute(() -> copyBatchNewAuditHistory(sourceServiceProviderId, targetServiceProviderId, targetServiceProviderAuditId));
        return true;
    }

    /**
     * 创建服务商审核历史QueryWrapper
     *
     * @param query ServiceProviderAuditHistoryDTO.
     * @return QueryWrapper.
     */
    private QueryWrapper<ServiceProviderAuditHistory> createServiceProviderAuditHistoryQueryWrapper(ServiceProviderAuditHistoryDTO query) {
        QueryWrapper<ServiceProviderAuditHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ServiceProviderAuditHistory::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(query.getServiceProviderAuditId() != null,
                        ServiceProviderAuditHistory::getServiceProviderAuditId, query.getServiceProviderAuditId())
                .eq(query.getServiceProviderId() != null,
                        ServiceProviderAuditHistory::getServiceProviderId, query.getServiceProviderId())
        ;
        return queryWrapper;
    }
}
